package com.rtsapp.server.platform.onesdk;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.rtsapp.server.app.AppConfig;
import com.rtsapp.server.platform.IPlatformLoginService;
import com.rtsapp.server.logger.Logger;

import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.text.MessageFormat;

/**
 * Created by admin on 16-3-10.
 */
public class OneSdkLoginService implements IPlatformLoginService {

    private static final String URL = AppConfig.getInstance().getYiJieSdkUrl();
    private static final Logger LOGGER = com.rtsapp.server.logger.LoggerFactory.getLogger( OneSdkLoginService.class );

    @Override
    public String validateLoginToken(String token, String uid) {

        JSONObject jsonObject = JSON.parseObject(token);
        String sdk = jsonObject.getString("sdkid");
        String appid = jsonObject.getString("appid");
        String token2 = jsonObject.getString("token");
        String uid2 = jsonObject.getString("uid");

        String url = MessageFormat.format("{0}?sdk={1}&app={2}&uin={3}&sess={4}",URL, sdk, appid, uid2==null||"".equals(uid)?token2:uid2, token2);
        if (valid(url)) {
            return "1sdk_" + uid2;
        }
        return null;
    }

    private boolean valid(String url) {

        HttpGet httpGet = new HttpGet(url);
        httpGet.addHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
        RequestConfig config = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).setAuthenticationEnabled(false).build();
        httpGet.setConfig(config);

        try (CloseableHttpClient http = HttpClients.createDefault(); CloseableHttpResponse response = http.execute(httpGet)){
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                if (EntityUtils.toString(response.getEntity()).equals("0")) {
                    return true;
                }
            }
            return false;
        } catch (IOException e) {
            LOGGER.error("向易接服务器请求登录验证时出现异常:",e);
            return false;
        }
    }

}
